using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TjZheng.CMS.Process;
using TjZheng.Controls;
using TjZheng.Framework;
using TjZheng.Power.Business;
using TjZheng.Power.DataEntity;
using TjZheng.CMS.Process.Business;
using Aspose.Cells;
using System.Data;
using TjZheng.Redis;
using TjZheng.Power.RedisEntity;
using TjZheng.Cache;

namespace TjZheng.CMS.Controllers
{
    public class UserInfoController : CMSController
    {
        /// <summary>
        /// 业务逻辑层
        /// </summary>
        BizUserInfo objBizUserInfo { get; set; }
        public UserInfoController()
        {
            objBizUserInfo = new BizUserInfo();
        }
        /// <summary>
        /// 列表页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 列表数据或搜索数据
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">页条数</param>
        /// <returns></returns>
        [QueryMsSqlFilter]
        [AuthorizeFilter(PowerType.CheckLogin)]
        public ActionResult ListJson(int page, int rows)
        {
            return Json(objBizUserInfo.GetPageResult(page - 1, rows, QueryResult.Condition, QueryResult.Parameters, "Id"));
        }
        /// <summary>
        /// 用户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult DetailInfo()
        {
            return View();
        }
        /// <summary>
        /// 编辑信息
        /// </summary>
        /// <returns></returns>
        public ActionResult EditInfo()
        {
            UserInfo objTarget = objBizUserInfo.GetRecord(CurrentUser.Id);
            if (objTarget == null)
            {
                return Content("对不起，您的帐号已被管理员移除，请联系管理员");
            }
            return View(objTarget);
        }
        /// <summary>
        /// 编辑信息-保存
        /// </summary>
        /// <param name="objProvide"></param>
        /// <returns></returns>
        public ActionResult SaveInfo(UserInfo objProvide)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (objProvide == null)
            {
                objInvokeResult.ResultCode = "ProvideNull";
                objInvokeResult.ResultMessage = "保存失败";
                return Json(objInvokeResult, "text/plain");
            }
            UserInfo objTarget = objBizUserInfo.GetRecord(objProvide.Id);
            if (objTarget == null)
            {
                objInvokeResult.ResultCode = "TargetNull";
                objInvokeResult.ResultMessage = "对不起，您的帐号已被管理员移除，请联系管理员";
                return Json(objInvokeResult, "text/plain");
            }
            objProvide.Password = objTarget.Password;
            objProvide.PowerType = objTarget.PowerType;
            Save(objTarget, objProvide);
            objBizUserInfo.Update(objTarget);
            if (IsCheckUserPowerRedis)
            {
                objBizUserInfo.Store(objTarget, PowerVariable.ProviderName, PowerVariable.Db);
            }
            else
            {
                objBizUserInfo.DeleteIDCache(objTarget.Id);
                FormAuthHelper.SetUserTicket(objTarget.UserName, objTarget, DateTime.Now.AddHours(2), true);
            }
            objInvokeResult.ResultMessage = "保存成功";
            return Json(objInvokeResult, "text/plain");
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        public ActionResult EditPassword()
        {
            UserInfo objTarget = objBizUserInfo.GetRecord(CurrentUser.Id);
            if (objTarget == null)
            {
                return Content("对不起，您的帐号已被管理员移除，请联系管理员");
            }
            return View(objTarget);
        }
        /// <summary>
        /// 修改密码-保存
        /// </summary>
        /// <param name="OldPassword"></param>
        /// <param name="NewPassword"></param>
        /// <param name="CheckPassword"></param>
        /// <returns></returns>
        public ActionResult SavePassword(string OldPassword, string NewPassword, string CheckPassword)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (!string.Equals(NewPassword, CheckPassword))
            {
                objInvokeResult.ResultCode = "NewPasswordNotEqual";
                objInvokeResult.ResultMessage = "对不起，两次输入的密码不一致";
                return Json(objInvokeResult, "text/plain");
            }
            UserInfo objTarget = objBizUserInfo.GetRecord(CurrentUser.Id);
            if (objTarget == null)
            {
                objInvokeResult.ResultCode = "TargetNull";
                objInvokeResult.ResultMessage = "对不起，您的帐号已被管理员移除，请联系管理员";
                return Json(objInvokeResult, "text/plain");
            }
            if (!string.Equals(OldPassword.EncodeMD5(), objTarget.Password))
            {
                objInvokeResult.ResultCode = "OldPasswordNotEqual";
                objInvokeResult.ResultMessage = "对不起，您输入的旧密码有误";
                return Json(objInvokeResult, "text/plain");
            }
            objTarget.Password = NewPassword.EncodeMD5().CutWord(64);
            objBizUserInfo.Update(objTarget);
            if (IsCheckUserPowerRedis)
            {
                objBizUserInfo.Store(objTarget, PowerVariable.ProviderName, PowerVariable.Db);
            }
            else
            {
                objBizUserInfo.DeleteIDCache(objTarget.Id);
            }
            UserProcess objUserProcess = new UserProcess();
            objUserProcess.LoginOut();
            objInvokeResult.ResultMessage = "修改成功，请重新登录";
            return Json(objInvokeResult, "text/plain");
        }
        /// <summary>
        /// 编辑页面
        /// </summary>
        /// <param name="id">数据id</param>
        /// <returns></returns>
        public ActionResult EditPage(long? id)
        {
            UserInfo objUserInfo = null;
            if (id.HasValue)
            {
                objUserInfo = objBizUserInfo.GetRecord(id.Value);
            }
            else
            {
                objUserInfo = new UserInfo();
            }
            return View(objUserInfo);
        }
        /// <summary>
        /// 编辑页面-保存
        /// </summary>
        /// <param name="objProvide">数据源</param>
        /// <returns></returns>
        //[ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Save(UserInfo objProvide)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (objProvide == null)
            {
                objInvokeResult.ResultCode = "ProvideNull";
                objInvokeResult.ResultMessage = "保存失败";
                return Json(objInvokeResult, "text/plain");
            }
            UserInfo objTarget = null;
            if (objProvide.Id <= 0)
            {
                objTarget = new UserInfo();
                Save(objTarget, objProvide);
                if (objBizUserInfo.Any("UserName=@UserName", "UserName".CreateSqlParameters(objTarget.UserName)))
                {
                    objInvokeResult.ResultCode = "AlreadyExist";
                    objInvokeResult.ResultMessage = "已存在用户名：" + objTarget.UserName;
                    return Json(objInvokeResult, "text/plain");
                }
                objTarget.LoginDate = DateTime.Now;
                objTarget.CreateDate = DateTime.Now;
                objTarget.Id = objBizUserInfo.Add(objTarget);
            }
            else
            {
                objTarget = objBizUserInfo.GetRecord(objProvide.Id);
                if (objTarget == null)
                {
                    objInvokeResult.ResultCode = "DataNull";
                    objInvokeResult.ResultMessage = "保存失败";
                    return Json(objInvokeResult, "text/plain");
                }
                Save(objTarget, objProvide);
                objBizUserInfo.Update(objTarget);
                objBizUserInfo.DeleteIDCache(objTarget.Id);
            }
            if (IsCheckUserPowerRedis)
            {
                objBizUserInfo.Store(objTarget, PowerVariable.ProviderName, PowerVariable.Db);
                BizUserRoleInfo objBizUserRoleInfo = new BizUserRoleInfo();
                UserRole objUserRole = new UserRole
                {
                    UserId = objTarget.Id,
                    GroupIds = objBizUserRoleInfo.GetFieldList<long>("UserId=" + objTarget.Id, "GroupId")
                };
                RedisHelper.Store<UserRole>(objUserRole, PowerVariable.ProviderName, PowerVariable.Db);
            }
            objInvokeResult.ResultCode = "Success";
            objInvokeResult.ResultMessage = "保存成功";
            return Json(objInvokeResult, "text/plain");
        }
        /// <summary>
        /// 列表页面-删除
        /// </summary>
        /// <param name="id">数据id或id集合</param>
        /// <returns></returns>
        public ActionResult Delete(string id)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (id.IsNull())
            {
                objInvokeResult.ResultCode = "IDNull";
                objInvokeResult.ResultMessage = "请先选择一条数据";
                return Json(objInvokeResult, "text/plain");
            }
            UserProcess objUserProcess = new UserProcess();
            var objUserIds = id.Split(',').Select(c => Convert.ToInt64(c)).ToList();
            objInvokeResult = objUserProcess.DeleteUsers(objUserIds);
            return Json(objInvokeResult, "text/plain");
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        [QueryMsSqlFilter]
        public ActionResult Export()
        {
            WorkbookDesigner objWorkbookDesigner = new WorkbookDesigner();
            objWorkbookDesigner.Open(Server.MapPath("~/Views/UserInfo/UserInfoList.xls"));
            var objDataTable = objBizUserInfo.GetDataTable(QueryResult.Condition, QueryResult.Parameters);
            objDataTable.TableName = "UserInfo";
            objDataTable.Columns.Add("PowerTypeString", typeof(string));
            objDataTable.Columns.Add("SexString", typeof(string));
            string objPowerTypeString = string.Empty;
            foreach (DataRow objRow in objDataTable.Rows)
            {
                switch (objRow["PowerType"].ToString())
                {
                    case "0":
                        objPowerTypeString = "继承角色组部分权限";
                        break;
                    case "1":
                        objPowerTypeString = "继承角色组所有权限";
                        break;
                    case "2":
                        objPowerTypeString = "用户独立权限";
                        break;
                }
                objRow["PowerTypeString"] = objPowerTypeString;
                objRow["SexString"] = objRow["Sex"].ToString() == "0" ? "男" : "女";
            }
            objWorkbookDesigner.SetDataSource(objDataTable);
            objWorkbookDesigner.Process();
            string fileName = Server.MapPath("~/Docs/用户信息.xls");
            //objWorkbookDesigner.Save(fileName, SaveType.OpenInExcel, FileFormatType.Excel2003, Response);
            fileName.CreateDirectory();
            objWorkbookDesigner.Save(fileName, FileFormatType.Excel2003);
            return File(fileName, "application/ms-excel", "用户信息.xls");
        }
        /// <summary>
        /// 同步Redis缓存
        /// </summary>
        /// <param name="id">用户组Id</param>
        /// <returns></returns>
        public ActionResult SyncRedis(int id)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (id <= 0)
            {
                objInvokeResult.ResultCode = "ParameterError";
                objInvokeResult.ResultMessage = "参数错误";
                return Json(objInvokeResult, "text/plain");
            }
            UserInfo objUserInfo = objBizUserInfo.GetRecord(id);
            if (objUserInfo == null)
            {
                objInvokeResult.ResultCode = "DataNull";
                objInvokeResult.ResultMessage = "没有相关的数据同步";
                return Json(objInvokeResult, "text/plain");
            }

            if (IsCheckUserPowerRedis)
            {
                objBizUserInfo.Store(objUserInfo, PowerVariable.ProviderName, PowerVariable.Db);
                BizUserRoleInfo objBizUserRoleInfo = new BizUserRoleInfo();
                UserRole objUserRole = new UserRole
                {
                    UserId = objUserInfo.Id,
                    GroupIds = objBizUserRoleInfo.GetFieldList<long>("UserId=" + objUserInfo.Id, "GroupId")
                };
                RedisHelper.Store<UserRole>(objUserRole, PowerVariable.ProviderName, PowerVariable.Db);

                BizUserPowerInfo objBizUserPowerInfo = new BizUserPowerInfo();
                UserPower objUserPower = new UserPower
                {
                    UserId = objUserInfo.Id,
                    PowerIds = objBizUserPowerInfo.GetFieldList<long>("UserId=" + objUserInfo.Id, "PowerId")
                };
                RedisHelper.Store<UserPower>(objUserPower, PowerVariable.ProviderName, PowerVariable.Db);

                objBizUserPowerInfo = new BizUserPowerInfo("Dependent");
                objUserPower = new UserPower
                {
                    UserId = objUserInfo.Id,
                    PowerIds = objBizUserPowerInfo.GetFieldList<long>("UserId=" + objUserInfo.Id, "PowerId")
                };
                RedisHelper.Store<UserPower>(objUserPower, PowerVariable.ProviderName, PowerVariable.Db, "Dependent");
            }

            objInvokeResult.ResultMessage = "同步成功";
            return Json(objInvokeResult, "text/plain");
        }
        /// <summary>
        /// 数据赋值
        /// </summary>
        /// <param name="objTarget">目标数据</param>
        /// <param name="objProvide">数据源</param>
        void Save(UserInfo objTarget, UserInfo objProvide)
        {
            objTarget.UserName = objProvide.UserName.CutWord(64);
            objTarget.RealName = objProvide.RealName.CutWord(64);
            if (objTarget.Password.IsNull() || !string.Equals(objTarget.Password, objProvide.Password))
            {
                objTarget.Password = objProvide.Password.EncodeMD5().CutWord(64);
            }
            objTarget.PowerType = objProvide.PowerType;
            objTarget.Sex = objProvide.Sex;
            objTarget.QQ = objProvide.QQ.CutWord(64);
            objTarget.Telephone = objProvide.Telephone.CutWord(64);
            objTarget.Email = objProvide.Email.CutWord(64);
            objTarget.Address = objProvide.Address.CutWord(128);
            objTarget.Avatar = objProvide.Avatar.SaveFiles("objProvide.Avatar");
            objTarget.Department = objProvide.Department.CutWord(64);
            objTarget.Description = objProvide.Description.CutWord(512);
            //objTarget.LoginIP = objProvide.LoginIP.CutWord(64);
            //objTarget.LoginDate = objProvide.LoginDate;
            //objTarget.CreateDate = objProvide.CreateDate;
        }
    }
}
